class DataManager {
    constructor() {
        this.attributeCount = 0;
        this.bindEventHandlers();
        this.loadPlaces();
    }

    // 绑定事件处理器
    bindEventHandlers() {
        // 添加地点表单提交
        document.getElementById('addPlaceForm')?.addEventListener('submit', (e) => this.handleAddPlace(e));

        // 添加属性按钮
        document.getElementById('addAttributeBtn')?.addEventListener('click', () => this.addAttributeField());

        // 导入导出按钮
        document.getElementById('importBtn')?.addEventListener('click', () => this.showImportDialog());
        document.getElementById('exportBtn')?.addEventListener('click', () => this.handleExport());

        // 导入表单提交
        document.getElementById('importForm')?.addEventListener('submit', (e) => this.handleImport(e));

        // 搜索输入
        document.getElementById('searchInput')?.addEventListener('input', (e) => this.handleSearch(e.target.value));
    }

    // 添加属性字段
    addAttributeField() {
        const container = document.getElementById('attributesContainer');
        if (!container) return;

        const fieldId = this.attributeCount++;
        const field = document.createElement('div');
        field.className = 'attribute-field';
        field.innerHTML = `
            <input type="text" class="form-input" name="attr_name_${fieldId}" placeholder="属性名" required>
            <input type="text" class="form-input" name="attr_value_${fieldId}" placeholder="属性值" required>
            <button type="button" class="btn btn-danger" onclick="dataManager.removeAttributeField(this)">
                <i class="fas fa-times"></i>
            </button>
        `;

        container.appendChild(field);
    }

    // 移除属性字段
    removeAttributeField(button) {
        const field = button.parentElement;
        field.remove();
    }

    // 处理添加地点
    async handleAddPlace(e) {
        e.preventDefault();

        try {
            const formData = new FormData(e.target);
            const placeData = {
                name: formData.get('name'),
                category: formData.get('category'),
                longitude: parseFloat(formData.get('longitude')),
                latitude: parseFloat(formData.get('latitude')),
                description: formData.get('description'),
                attributes: this.collectAttributes(formData)
            };

            const response = await PlacesAPI.addPlace(placeData);
            if (response.status === 'success') {
                alert('地点添加成功！');
                e.target.reset();
                this.loadPlaces();
            } else {
                throw new Error(response.message || '添加失败');
            }
        } catch (error) {
            console.error('添加地点错误:', error);
            alert('添加地点失败：' + error.message);
        }
    }

    // 收集属性数据
    collectAttributes(formData) {
        const attributes = [];
        for (let i = 0; i < this.attributeCount; i++) {
            const name = formData.get(`attr_name_${i}`);
            const value = formData.get(`attr_value_${i}`);
            if (name && value) {
                attributes.push({ name, value });
            }
        }
        return attributes;
    }

    // 加载地点列表
    async loadPlaces() {
        try {
            const response = await PlacesAPI.getAllPlaces();
            if (response.status === 'success') {
                this.displayPlaces(response.data);
            } else {
                throw new Error(response.message || '加载失败');
            }
        } catch (error) {
            console.error('加载地点列表错误:', error);
            alert('加载地点列表失败：' + error.message);
        }
    }

    // 显示地点列表
    displayPlaces(places) {
        const container = document.getElementById('placesList');
        if (!container) return;

        container.innerHTML = places.map(place => `
            <div class="place-item">
                <h3 class="text-lg font-semibold">${place.name}</h3>
                <p class="text-gray-600">${place.description || '暂无描述'}</p>
                <div class="mt-2">
                    ${place.category ? `<span class="tag">${place.category}</span>` : ''}
                    ${place.attributes?.map(attr => 
                        `<span class="tag">${attr.name}: ${attr.value}</span>`
                    ).join('') || ''}
                </div>
                <div class="actions">
                    <button class="btn btn-secondary" onclick="dataManager.editPlace('${place.id}')">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    <button class="btn btn-danger" onclick="dataManager.deletePlace('${place.id}')">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </div>
            </div>
        `).join('');
    }

    // 编辑地点
    async editPlace(id) {
        try {
            const place = await PlacesAPI.getPlace(id);
            if (place) {
                // TODO: 实现编辑功能
                alert('编辑功能开发中...');
            }
        } catch (error) {
            console.error('获取地点详情错误:', error);
            alert('获取地点详情失败：' + error.message);
        }
    }

    // 删除地点
    async deletePlace(id) {
        if (!confirm('确定要删除这个地点吗？')) return;

        try {
            const response = await PlacesAPI.deletePlace(id);
            if (response.status === 'success') {
                alert('地点删除成功！');
                this.loadPlaces();
            } else {
                throw new Error(response.message || '删除失败');
            }
        } catch (error) {
            console.error('删除地点错误:', error);
            alert('删除地点失败：' + error.message);
        }
    }

    // 显示导入对话框
    showImportDialog() {
        const dialog = document.getElementById('importDialog');
        if (dialog) {
            dialog.classList.add('active');
        }
    }

    // 关闭导入对话框
    closeImportDialog() {
        const dialog = document.getElementById('importDialog');
        if (dialog) {
            dialog.classList.remove('active');
        }
    }

    // 处理导入
    async handleImport(e) {
        e.preventDefault();

        const fileInput = document.getElementById('importFile');
        const file = fileInput?.files[0];
        if (!file) {
            alert('请选择要导入的文件');
            return;
        }

        try {
            const response = await PlacesAPI.importPlaces(file);
            if (response.status === 'success') {
                alert('数据导入成功！');
                this.closeImportDialog();
                this.loadPlaces();
            } else {
                throw new Error(response.message || '导入失败');
            }
        } catch (error) {
            console.error('导入数据错误:', error);
            alert('导入数据失败：' + error.message);
        }
    }

    // 处理导出
    async handleExport() {
        try {
            const blob = await PlacesAPI.exportPlaces();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `places_export_${new Date().toISOString().slice(0,10)}.json`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
        } catch (error) {
            console.error('导出数据错误:', error);
            alert('导出数据失败：' + error.message);
        }
    }

    // 处理搜索
    handleSearch(keyword) {
        // TODO: 实现搜索功能
        console.log('搜索:', keyword);
    }
}

// 创建数据管理器实例
window.dataManager = new DataManager(); 